<template>
  <div>
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item
        label="用户名"
        prop="username"
      >
        <el-input
          v-model="ruleForm.username"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="密码"
        prop="passwordMd5"
      >
        <el-input
          type="password"
          v-model="ruleForm.passwordMd5"
          autocomplete="off"
          @change="submitForm('ruleForm')"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          :loading="!flag"
          @click="submitForm('ruleForm')"
        >提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
// @ is an alias to /src
import md5 from "md5";
import { login } from "../api/api";
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("passwordMd5");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };

    return {
      ruleForm: {
        username: "",
        passwordMd5: "",
      },
      rules: {
        pass: [{ validator: validatePass, trigger: "blur" }],
        checkPass: [{ validator: validatePass2, trigger: "blur" }],
      },
      flag: true,
    };
  },
  methods: {
    submitForm(formName) {
      console.log(666);
      if (!this.flag) return;
      this.flag = false;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let obj = {};
          obj.passwordMd5 = md5(this.ruleForm.passwordMd5);
          obj.userName = this.ruleForm.username;
          // console.log(obj);
          login(obj).then((data) => {
            // console.log(data);
            localStorage.setItem("xf_project_token", data.data);
            if (this.$route.query.from) {
              console.log("this.$route.query.from", this.$route.query.from);
              this.$router.replace(this.$route.query.from);
            } else {
              this.$router.replace("/");
            }
            this.flag = true;
            // window.location.href='';
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>
<style lang="less">
</style>